package client.comm.baoding

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.multidex.MultiDexApplication
import client.comm.commlib.App
import client.comm.commlib.ContextProvider
import client.comm.commlib.SimpleLifecycleCallbacks
import client.comm.commlib.base.FinishReciver
import client.comm.commlib.utils.SharedUtil
import client.comm.baoding.ui.LoginActivity
import com.alipay.sdk.app.APayEntranceActivity
import com.alipay.sdk.app.H5PayActivity
import com.alipay.sdk.app.PayResultActivity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils

class MyApp : MultiDexApplication() {

    //单例化的第一种方式：声明一个简单的Application属性
    companion object {
        const val TAG = "logbd"

        //情况一：声明可空的属性
        private var instance: MyApp? = null
        fun getInstance() = instance!!
        //情况二：声明延迟初始化属性
        //private lateinit var instance: MainApplication
        //fun instance() = instance
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        instance = this
    }


    override fun onCreate() {
        super.onCreate()
        instance = this
        initConfig()
    }

    private fun initConfig() {
        LogUtils.getConfig().setGlobalTag("blankj")
        registerLifecycle()
    }

    private fun registerLifecycle() {
        registerActivityLifecycleCallbacks(object : SimpleLifecycleCallbacks() {

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                ContextProvider.get().attach(activity, {
                    SharedUtil.clear("token")
                    it?.let {
                        it.startActivity(Intent(it, LoginActivity::class.java))
                        activity.sendBroadcast(Intent(FinishReciver.FINISH_ACTION))
                    }
                })
            }

            override fun onActivityResumed(activity: Activity) {
                Log.d("MyApp", activity.localClassName)

                ContextProvider.get().attach(activity, {
                    SharedUtil.clear("token")
                    it?.let {
                        it.startActivity(Intent(it, LoginActivity::class.java))
                        activity.sendBroadcast(Intent(FinishReciver.FINISH_ACTION))
                    }
                })


            }

            override fun onActivityStopped(activity: Activity) {}

            override fun onActivityDestroyed(activity: Activity) {
                //                ContextProvider.get().detach()
            }
        })
    }


}